package reviewAlgorithms.search;

import java.util.ArrayList;
import java.util.List;

public class RestoreIpAddresses {
    public static void main(String[] args) {
        String s = "1111";
        List<String> res = restoreIpAddresses(s);
        for (String str: res) {
            System.out.println(str);
        }
    }
    public static List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<>();
        if (s == null || s.length() < 1 || s.length() > 12){
            return res;
        }
        List<int[]> indexRes = new ArrayList<>();
        int[] oneRes = new int[3];
        getIndexRes(s,0,0,indexRes,oneRes);
        for (int[] item : indexRes) {
            StringBuilder temp = new StringBuilder();
            int startIndex = 0;
            for (int i = 0; i < item.length; i++) {
                temp.append(s, startIndex, item[i] + 1);
                temp.append('.');
                startIndex = item[i] + 1;
            }
            temp.append(s,startIndex,s.length());
            res.add(temp.toString());
        }
        return res;
    }

    private static void getIndexRes(String s, int n,int start, List<int[]> indexRes, int[] oneRes) {
        if (n >= 3){
            String sub = s.substring(start);
            if (s.charAt(start) == '0' && sub.length() == 1 || s.charAt(start) != '0' && Long.valueOf(sub) <= 255){
                int[] temp = oneRes.clone();
                indexRes.add(temp);
            }
            return;
        }
        int offset = 3;
        if (s.charAt(start) == '0'){
            offset = 1;
        }
        for (int i = start; i < start + offset; i++) {
            if (i >= s.length() - 1){
                return;
            }
            String sub = s.substring(start,i + 1);
            if (Integer.valueOf(sub) <= 255){
                oneRes[n] = i;
                getIndexRes(s,n + 1,i + 1,indexRes,oneRes);
            }
        }

    }
}
